<template>
  <div class="send-activity-research-view">
    <!-- slot -->
    <slot>
      <el-button type="plain-third" @click="handleCreate" v-track="$track.formatParams('SEND_ACTIVITY_RESEARCH')">
        {{$t('customer.sendActivitySurvey')}}
      </el-button>
    </slot>

    <!-- 选择现有活动 -->
    <el-dialog
      :title="$t('customer.sendActivitySurvey')"
      :visible.sync="visible"
      width="600px"
      @close="handleCloseDialog"
    >
      <el-form
        label-position="top"
        ref="formRef"
        :model="form"
        
        :rules="rules"
      >
        <el-form-item :label="$t('customer.sendActivitySurveyDialog.form.activities.label')" prop="activities">
          <div class="activities-item">
            <biz-remote-select
              :placeholder="$t('customer.sendActivitySurveyDialog.form.activities.placeholder')"
              :value="form.activities"
              :cleared="true"
              :remote-method="searchActivityList"
              @input="selectActivity"
            >
              <div slot="option" slot-scope="{ option }">
                <div>{{ option.activitiesName }}</div>
              </div>
            </biz-remote-select>
            <el-tooltip
              placement="top"
              :content="$t('customer.sendActivitySurveyDialog.form.activities.tip')">
              <i class="el-icon-question el-tooltip mar-l-8 mar-r-8"></i>
            </el-tooltip>
            <el-button type="text" @click="createNewActivity">
              {{$t('customer.sendActivitySurveyDialog.form.activities.button')}}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item v-if="form.activitiesId" :label="$t('customer.sendActivitySurveyDialog.form.sendSetting.label')" prop="sendSetting">
          <el-checkbox-group v-model="form.sendSetting">
            <el-checkbox label="1">{{$t('customer.sendActivitySurveyDialog.form.sendSetting.checkbox[1]')}}</el-checkbox>
            <el-checkbox label="2">{{$t('customer.sendActivitySurveyDialog.form.sendSetting.checkbox[2]')}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item v-if="form.activitiesId" :label="$t('customer.sendActivitySurveyDialog.form.receiveUserType.label')">
          <el-radio-group v-model="form.receiveUserType">
            <el-radio :label="0">{{$t('customer.sendActivitySurveyDialog.form.receiveUserType.checkbox[0]')}}</el-radio>
            <el-radio :label="1">{{$t('customer.sendActivitySurveyDialog.form.receiveUserType.checkbox[1]')}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 短信 -->
        <template v-if="form.sendSetting.includes('1')">
          <el-form-item :label="$t('customer.sendActivitySurveyDialog.form.smsTemplateId.label')" prop="smsTemplateId">
            <el-select v-model="form.smsTemplateId">
              <el-option
                v-for="item in messageTemplate"
                :label="item.name"
                :value="item.id"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('customer.sendActivitySurveyDialog.form.template.label')">
            <el-input
              v-model="template"
              type="textarea"
              rows="5"
              resize="none"
              disabled
            ></el-input>
          </el-form-item>
        </template>

        <!-- 邮件 -->
        <template v-if="form.sendSetting.includes('2')">
          <el-form-item :label="$t('customer.sendActivitySurveyDialog.form.emailSubject.label')" prop="emailSubject">
            <el-input v-model="form.emailSubject"></el-input>
          </el-form-item>
          <el-form-item :label="$t('customer.sendActivitySurveyDialog.form.emailTemplateContent.label')" prop="emailTemplateContent">
            <el-input
              v-model="form.emailTemplateContent"
              type="textarea"
              rows="5"
              resize="none"
            ></el-input>
            <div class="email-tips font-12 color-999">{{$t('customer.sendActivitySurveyDialog.form.emailTemplateContent.emailTemplateContentTip')}}</div>
          </el-form-item>
        </template>

        <el-form-item :label="$t('customer.sendActivitySurveyDialog.form.sendTime.label')" prop="sendTime" :error="error">
          <div class="flex-x">
            <el-radio v-model="form.sendTimeType" :label="1" @change="sendTimeTypeChange">{{ $t('common.base.immediately') }}</el-radio>
            <el-radio class="mar-l-24" v-model="form.sendTimeType" :label="2" @change="sendTimeTypeChange">{{ $t('common.base.atRegularTime') }}</el-radio>
            <el-date-picker
              class="mar-l-12"
              popper-class="message-date-picker"
              v-show="form.sendTimeType === 2"
              v-model="form.sendTime"
              type="datetime"
              :placeholder="$t('customer.sendActivitySurveyDialog.form.sendTime.placeholder')"
              :picker-options="datePickerOption"
              default-time="12:00"
              format="yyyy-MM-dd HH:mm"
              value-format="timestamp"
            >
            </el-date-picker>
          </div>
          
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="visible = false">{{$t('common.base.cancel')}}</el-button>
        <el-button
          type="primary"
          :loading="pending"
          @click="confirmCreateExistActivity"
        >
          {{$t('common.base.confirm')}}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as CustomerApi from '@src/api/CustomerApi.ts';
import { safeNewDate } from '@src/util/time';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { openAccurateTab } from '@src/util/platform'
import i18n from '@src/locales'
import moment from 'moment'

export default {
  name: 'send-activity-research',
  props: {
    mode: {
      type: String,
      default: 'CUSTOMER', // CUSTOMER, PRODUCT
    },
    // 选中列表的数据
    selection: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      visible: false,
      pending: false,
      options: [],
      messageTemplate: [],
      form: {
        activities: [],
        sendSetting: [],
        receiveUserType: 0,
        activitiesId: '',
        smsTemplateId: '',
        emailSubject: '',
        emailTemplateContent: i18n.t('customer.sendActivitySurveyDialog.form.emailTemplateContent.emailTemplateContent'),
        sendTime: moment(+new Date()).valueOf(),
        sendTimeType: 1,
      },
      datePickerOption: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
      error: '',
      rules: {
        activities: [
          {
            required: true,
            message: i18n.t('customer.sendActivitySurveyDialog.form.activities.rule.required'),
            trigger: ['blur', 'change'],
          },
        ],
        emailSubject: [
          {
            required: true,
            message: i18n.t('customer.sendActivitySurveyDialog.form.emailSubject.rule.required'),
            trigger: ['blur', 'change'],
          },
        ],
        emailTemplateContent: [
          {
            required: true,
            message: i18n.t('customer.sendActivitySurveyDialog.form.emailTemplateContent.rule.required'),
            trigger: ['blur', 'change'],
          },
        ],
      },
    };
  },
  computed: {
    idsList() {
      let list = [];
      if (this.selection && this.selection.length) {
        list = this.selection.map(item => {
          return item.id;
        });
      }
      return list;
    },
    template() {
      return this.messageTemplate
        .filter(t => t.id === this.form.smsTemplateId)
        .map(t => t.allowContent)
        .join('');
    },
  },
  created() {
    // this.searchActivityList();
  },
  methods: {
    sendTimeTypeChange() {
      this.error = '';
    },
    // 获取短信模板
    fetchTemplate() {
      this.$http
        .get('/vipsms/getTemplates', { pageSize: '100', pageNum: '1' })
        .then(res => {
          if (res.status) {
            this.$platform.alert(this.$t('customer.sendActivitySurveyDialog.fetchTemplate.failMsg'));
          }
          this.messageTemplate = (res.data.list || []).filter(
            t =>
              (t.notice === '自定义通知' || t.notice === '客户体验调研通知' || t.type == 1) &&
              t.status === 'pass_approval'
          );
          if (this.messageTemplate.length) {
            this.form.smsTemplateId = this.messageTemplate[0].id;
          }
        })
        .catch(err => {
          console.error('fetchTemplate', err);
          this.$platform.alert(this.$t('customer.sendActivitySurveyDialog.fetchTemplate.failMsg'));
        });
    },

    // 点击发送活动调研按钮
    handleCreate() {
      if (this.selection && this.selection.length) {
        this.fetchTemplate();
        this.visible = true;
      } else {
        return this.$platform.alert(this.$t('customer.sendActivitySurveyDialog.handleCreate.noSelectMsg'));
      }
    },

    // 选择现有活动
    confirmCreateExistActivity() {
      let { sendTime, sendTimeType } = this.form;
      this.error = '';

      if (sendTimeType == 2) {
        if (!sendTime) {
          return this.error = i18n.t('common.validate.requiredSendTime');
        } else if(sendTime < +new Date()) {
          return this.error = i18n.t('common.validate.invalidSendTime');
        }
      }

      this.$refs.formRef.validate(async valid => {
        if (valid) {
          let messageText = this.$t('customer.sendActivitySurveyDialog.confirmCreateExistActivity.successMsg');
          if (
            this.form.activities.length &&
            this.form.activities[0].activitiesStartTime
          ) {
            // 判断一下日期，做对应处理
            const startTime = safeNewDate(
              this.form.activities[0].activitiesStartTime
            ).getTime();

            if (sendTimeType == 1) {
              sendTime = moment(+new Date()).valueOf();
            }
            if (sendTime < startTime) {
              messageText = this.$t('customer.sendActivitySurveyDialog.confirmCreateExistActivity.notStartMsg');
            }
          }

          const ids = this.selection.map(item => {
            return item.id;
          });

          let payload = {
            ...this.form,
            customerIds: this.mode === 'CUSTOMER' ? ids : [],
            productIds: this.mode === 'PRODUCT' ? ids : [],
            personType: this.mode,
          };
          delete payload.activities;
          // 选择立即时，发送时间为当前时间
          if (sendTimeType == 1) {
            payload.sendTime = moment(+new Date()).valueOf();
          }

          this.pending = true;
          CustomerApi.sendActivities(payload)
            .then(result => {
              this.pending = false;
              const { message, success } = result;
              this.$platform.notification({
                title: success ? this.$t('common.base.success') : this.$t('common.base.fail'),
                message: success ? messageText : message,
                type: success ? 'success' : 'error',
              });

              if (success) {
                this.handleCloseDialog();
              }
            })
            .catch(err => console.err(err));
        } else {
          return false;
        }
      });
    },

    // 选择新活动
    createNewActivity() {
      // 把customerList存本地在活动新建页面获取
      sessionStorage.setItem(
        'ACTIVITY_RESEARCH_PRIMARY_IDS',
        JSON.stringify(this.idsList)
      );
      const fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: 'customer_experience_activity_research_create',
      //   title: '新建活动',
      //   url: `/pcoperation/customerExperience/activityResearch/create?from=${this.mode}`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCreateActivity,
        params: `from=${this.mode}`,
        fromId,
      })
    },

    // 关闭弹窗
    handleCloseDialog() {
      this.reset();
      this.visible = false;
    },

    // 选中活动
    selectActivity(value) {
      if(value && value.length) {
        this.form = {
          ...this.form,
          activities: value,
          activitiesId: value[0].id,
        }
      } else {
        this.reset();
      }
    },

    // 获取活动列表
    async searchActivityList(params) {
      try {
        let { result } = await CustomerApi.getActivitiesList(params);
        if (!result || !result.list) return;
        result.list = result.list.map(item => {
          return {
            label: item.activitiesName,
            value: item.id,
            ...item,
          };
        });

        return result;
      } catch (error) {
        console.warn('选择现有活动: searchActivityList -> error', error);
      }
    },

    // 重置表单
    reset() {
      this.$refs.formRef.resetFields();
      this.form = {
        activities: [],
        sendSetting: [],
        receiveUserType: 0,
        activitiesId: '',
        smsTemplateId: '',
        emailSubject: '',
        emailTemplateContent: i18n.t('customer.sendActivitySurveyDialog.form.emailTemplateContent.emailTemplateContent'),
        sendTime: moment().add(1, 'minute').valueOf(),
        sendTimeType: 1,
      };
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 30px 20px;
  border-bottom: 0;
  .activities-item {
    display: flex;
    align-items: center;
  }
  .el-form {
    .flex-x {
      .el-radio {
        line-height: 32px;
        margin-right: 0;
        &.mar-l-24 {
          margin-left: 24px;
        }
      }
    }
  }
}
.message-date-picker {
  .el-picker-panel__footer .el-button--text.el-picker-panel__link-btn {
    display: none;
  }
}
</style>
